<?php

class Application_Model_BlogService extends Base_Service
{
   /**
    * 
    * create blog
    * @param unknown_type $uid login user id 
    * @param Application_Model_BusiInfo_Blog $blog blog information
    */
	public function create($uid, Application_Model_BusiInfo_Blog $blog) {
		$db = $this->getDbAdapter();
		
		$row = array ( 
		'title' => $blog->getTitle(),
		'content' => $blog->getContent(),
		'owner_id' => $uid,
		'create_date' => date('Y-m-d H:i:s'));
		$this->logger->debug(__METHOD__. '   ' .$row);	

		$db->beginTransaction();
		$rows_affected = $db->insert('blog', $row);
		$blogId = $db->lastInsertId();
		$this->logger->debug(__METHOD__. '   ' .$blogId);
		
		$this->addTagsToBlog($blogId, $blog->getTags());
		$this->addCategoryToBlog($blogId, $blog->getCategory());
		$this->setPrivilege($blogId, $blog->getPrivilegeType());
		
		$db->commit();
		
		return $blogId;
		
	}
	
	/**
	 * 
	 * save edited blog
	 * @param unknown_type $uid login user id
	 * @param Application_Model_BusiInfo_Blog $blog blog information
	 */
	public function save($uid, Application_Model_BusiInfo_Blog $blog) {
		$db = $this->getDbAdapter();
		//TODO need to check if this user is the original owner
		$row = array ( 
		'title' => $blog->getTitle(),
		'content' => $blog->getContent(),
		'update_date' => date('Y-m-d H:i:s'));
		//$this->logger->debug(__METHOD__. '   ' .$row['update_date']);	

		$db->beginTransaction();
		$blogId = $blog->getBid();
		$rows_affected = $db->update('blog', $row, "bid=".$blogId);
		
		//$this->logger->debug(__METHOD__. '   ' .$blogId);
		
		//delete old tags blog relation
		$where = "content_type = 1 and content_id = ".$blogId;
		$this->logger->debug(__METHOD__. '   delete content_type where: ' .$where);
		$db->delete("content_tag", $where);
		
		$this->addTagsToBlog($blogId, $blog->getTags());	
		
		//delete old category
		$where = "bid = ".$blogId;
		$db->delete("blog_category", $where);
		if ($blog->getCategory()) {
			$this->addCategoryToBlog($blogId, $blog->getCategory());
		}
		
		//update privilege
		$where = "content_id = ".$blogId ." and content_type=".Application_Model_Constants::CONTENT_TYPE_BLOG;
		$db->delete("content_privilege", $where);
		$this->setPrivilege($blogId, $blog->getPrivilegeType());
		
		
		$db->commit();
	}
	
	/**
	 * 
	 * delete a blog
	 * @param unknown_type $uid login user id
	 * @param unknown_type $blogId blog id
	 */
	public function delete($uid, $blogId) {
		//TODO need to check if this user is the original owner
		$db = $this->getDbAdapter();
		$db->beginTransaction();		
		
		//delete tags blog relation
		$where = "content_type = ".Application_Model_Constants::CONTENT_TYPE_BLOG." and content_id = ".$blogId;
		$db->delete("content_tag", $where);
		
		//delete comments		
		$where = "content_type = ".Application_Model_Constants::CONTENT_TYPE_BLOG." and content_id = ".$blogId;
		$db->delete("comments", $where);
		
		//delete blog
		$where = "bid=".$blogId;
		$db->delete("blog", $where);
		
		$db->commit();
	}
	
	private function addTagsToBlog($bId, $tagStr) {
		$this->logger->debug(__METHOD__. '   $tagStr: '.$tagStr);
		$tagStr = trim($tagStr);
		$this->logger->debug(__METHOD__. '   $after trim tagStr: '.$tagStr);
		$tags = split('[ , ，]+', $tagStr);	
		$this->logger->debug(__METHOD__. '   $tags: '.var_dump($tags));
		$db = $this->getDbAdapter();
		$tagService = new Application_Model_TagService();		
		$tagService->setDbAdapter($db);
		foreach ($tags as $tag) {
			$this->logger->debug(__METHOD__. '   $tag before trim: '.$tag);
			$tag = trim($tag);
			$this->logger->debug(__METHOD__. '   $tag after trim: '.trim($tag));
			if($tag=="") {
				continue;
			}
			$tId = $tagService->getTagId($tag);
			//a new tag, need create in db
			if ($tId == -1) {
				$tId = $tagService->create($tag);
			}
			
			//add tag to this blog			
			$row = array ( 
				'content_id' => $bId,
				'content_type' => Application_Model_Constants::CONTENT_TYPE_BLOG,
				'tid' => $tId
			);
			$this->logger->debug(__METHOD__. '   ' .$row);
			$db->insert('content_tag', $row);			
			
		}		
	}
	
	private function addCategoryToBlog($bId, $cat) {
		$cat = trim($cat);
		if(!$cat) return;
		$db = $this->getDbAdapter();
		$catService = new Application_Model_CategoryService();		
		$catService->setDbAdapter($db);
		$catId = $catService->getCategoryId($cat);
		//a new category, need create in db
		if ($catId == -1) {
			$catId = $catService->create($cat);
		}
			
		//add catgory to this blog			
		$row = array ( 
			'bid' => $bId,
			'cat_id' => $catId
		);
		$db->insert('blog_category', $row);			
			
			
	}

	private function setPrivilege($bId, $pt) {
		$db = $this->getDbAdapter();
		$privilegeService = new Application_Model_PrivilegeTypeService();		
		$privilegeService->setDbAdapter($db);
		
					
		$row = array ( 
			'content_id' => $bId,
			'content_type' => Application_Model_Constants::CONTENT_TYPE_BLOG,
			'privilege_type' => $pt
		);
		$db->insert('content_privilege', $row);			
			
			
	}	
	
	public function getBlogTitle($uid = null) {
		$sql = "select b.uid, b.nickname, a.bid, a.create_date, a.title"
		." from blog a, user b"
		." where a.owner_id = b.uid";
		if ($uid) {
			$sql = $sql." and b.uid = ". $uid;
		}
		$sql = $sql." order by a.create_date desc"
		." limit 20";
		$this->logger->debug(__METHOD__." sql: ".$sql);
		$db = $this->getDbAdapter();
		$resultSet = $db->fetchAll($sql);
		return $resultSet;
	}
	
	/**
	 * 
	 * get blog count 
	 * @param unknown_type $uid login user id
	 * @param unknown_type $tagId selected tag id
	 * @param unknown_type $catId selected category id
	 * @param unknown_type $friendId  view member id
	 */
	 public function getBlogCount($uid=null, $tagId=null, $catId=null, $friendId=null)
	{
		$sql = $this->genSqlForSearch($uid, $tagId, $catId, $friendId, true);
		$this->logger->debug(__METHOD__." sql: ".$sql);
		$db = $this->getDbAdapter();
		$resultSet = $db->fetchAll($sql);		
		foreach ($resultSet as $row) {
			return $row['count'];			
		}
	}
	/**
	 * 
	 * fetch blogs
	 * @param unknown_type $uid login user id
	 * @param unknown_type $tagId selected tag id
	 * @param unknown_type $catId selected category id
	 * @param unknown_type $friendId  view friend id 
	 * @param unknown_type $offset offset of the records
	 * @param unknown_type $limit limit of the records
	 */
 	public function fetchBlogs($uid=null, $tagId=null, $catId=null, $friendId=null, $offset=null, $limit=null)
	{
		$sql = $this->genSqlForSearch($uid, $tagId, $catId, $friendId, false, $offset, $limit);
		$this->logger->debug(__METHOD__." sql: ".$sql);
		$db = $this->getDbAdapter();
		$resultSet = $db->fetchAll($sql);
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_BusiInfo_Blog();
			$entry->setBid($row['bid']);
			$entry->setTitle($row['title']);
			$entry->setContent($row['content']);
			$entry->setCreateDate($row['create_date']);
			$entry->setUpdateDate($row['update_date']);
			$this->logger->debug(__METHOD__." updatedate: ".$entry->getUpdateDate());	
			$entry->setOwnerId($row['owner_id']);
			$entry->setOwnerName($row['nickname']);
			//$entry->setViewCount($viewCount);	
			$entry->setTags($this->getTags($row['bid']));
			$entry->setCategoryId($row['cat_id']);
			$entry->setCategory($row['category']);
			$entry->setPrivilegeType($row['privilege_type']);			
			$entries[] = $entry;
		}
		return $entries;
	}
	
	private function genSqlForSearch($uid=null, $tagId=null, $catId=null, $friendId=null, $isCount=false, $offset=null, $limit=null)
	{
		if ($isCount) {
			$sql = "select count('x') count";
		} else {
			$sql = "select a.*, h.nickname, ".
			"(select e.cat_id from category e, blog_category d where a.bid=d.bid and e.cat_id = d.cat_id) cat_id, ".
			"(select e.category from category e, blog_category d where a.bid=d.bid and e.cat_id = d.cat_id) category, ".
			"(select g.privilege_type from content_privilege g where g.content_type=".Application_Model_Constants::CONTENT_TYPE_BLOG
				." and g.privilege_type=".Application_Model_Constants::PRIVILEGE_TYPE_PUBLIC." and a.bid=g.content_id ) privilege_type";
		}	
		$sql = $sql." from blog a, user h";
		if ($tagId) {
			$sql = $sql.",content_tag b";
		}
		if ($catId) {
			$sql = $sql.",blog_category c";
		}
		//user is not log in
		if (!$uid) {
			$sql = $sql.",content_privilege f";
		}
		
		$hasCon = false;
		
		$sql = $sql." where a.owner_id = h.uid";
		$hasCon = true;
		
		if ($tagId) {
			if ($hasCon) {
				$sql = $sql." and";
			} else {
				$sql = $sql." where";
			}
			$sql = $sql." a.bid=b.content_id and b.content_type=".Application_Model_Constants::CONTENT_TYPE_BLOG;
			$hasCon = true;
		}
		
		if ($catId) {
			if ($hasCon) {
				$sql = $sql." and";
			} else {
				$sql = $sql." where";
			}
			$sql = $sql." a.bid=c.bid";
			$hasCon = true;
		}
		//user is login
		if($uid != null) {
			if ($hasCon) {
				$sql = $sql." and";
			} else {
				$sql = $sql." where";
			}
			$sql = $sql." a.owner_id=".$uid;
			$hasCon = true;
		} else {
			if ($hasCon) {
				$sql = $sql." and";
			} else {
				$sql = $sql." where";
			}
			$sql = $sql." f.content_type=".Application_Model_Constants::CONTENT_TYPE_BLOG
			." and f.privilege_type=".Application_Model_Constants::PRIVILEGE_TYPE_PUBLIC
			." and f.content_id= a.bid";
			$hasCon = true;
		}
		if ($tagId) {
			if ($hasCon) {
				$sql = $sql." and";
			} else {
				$sql = $sql." where";
			}
			$sql = $sql." b.tid=".$tagId;
		}
		if ($catId) {
			if ($hasCon) {
				$sql = $sql." and";
			} else {
				$sql = $sql." where";
			}
			$sql = $sql." c.cat_id=".$catId;
		}
		if (!$isCount) {
			//no need to sort when get blog number
			$sql = $sql." order by a.create_date desc";
			if ($offset!=null && $limit!=null) {
			$sql = $sql." limit ".$limit." offset ".$offset;
		}

		}
		
		$this->logger->debug(__METHOD__." sql: ".$sql);
		return $sql;
	}
	
	private function getTags($bId) {
		$db = $this->getDbAdapter();
		return $db->fetchAll("select a.* from tag a, content_tag b "
		." where a.tid=b.tid and b.content_type = 1 and b.content_id = :blogId;",
		array("blogId"=>$bId));
	}
	
	/**
	 * 
	 * get blog info
	 * @param unknown_type $uid login user id
	 * @param unknown_type $blogId blog id
	 */
	public function getBlog($blogId) {
		$sql = "select a.*,".
			"(select e.cat_id from category e, blog_category d where a.bid=d.bid and e.cat_id = d.cat_id) cat_id, ".
			"(select e.category from category e, blog_category d where a.bid=d.bid and e.cat_id = d.cat_id) category, ".
			"(select g.privilege_type from content_privilege g where g.content_type=".Application_Model_Constants::CONTENT_TYPE_BLOG
			." and g.privilege_type=".Application_Model_Constants::PRIVILEGE_TYPE_PUBLIC." and a.bid=g.content_id ) privilege_type";
		$sql = $sql." from blog a where a.bid=".$blogId;
		$this->logger->debug(__METHOD__." sql: ".$sql);
		
		$db = $this->getDbAdapter();
		$resultSet = $db->fetchAll($sql);
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_BusiInfo_Blog();
			$entry->setBid($row['bid']);
			$entry->setTitle($row['title']);
			$entry->setContent($row['content']);
			$entry->setCreateDate($row['create_date']);
			$entry->setUpdateDate($row['update_date']);
			$this->logger->debug(__METHOD__." updatedate: ".$entry->getUpdateDate());	
			$entry->setOwnerId($row['owner_id']);
			//$entry->setViewCount($viewCount);	
			$entry->setTags($this->getTags($row['bid']));
			$entry->setCategoryId($row['cat_id']);
			$entry->setCategory($row['category']);
			$entry->setPrivilegeType($row['privilege_type']);			
			return $entry;
		}	
		
	}
	protected static $_instance = null;
	public static function getInstance() {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }	
}

